/*!
 * Copyright (c) 2007-2009, stauren.net. All rights reserved.
 * javascript and css loader of double-underscore, visit : http://code.google.com/p/double-underscore/
 * @file loader.js
 * @revision:
 * @author stauren@stauren.net
 */

(function(_scope) {

var DU_TAG = '0.2.0';

if (_scope['__'] == undefined) {
  _scope['__'] = {};
}
var __ = _scope['__'];

if (!__.load) {

  if (__.config == undefined) {
    __.config = {}
  }
  var _DOCUMENT = _scope.document, _SC = __.config,
    ua = navigator.userAgent, cua = _SC.ua = {}, loadingList;

  _SC.loaderBase = _SC.loaderBase || 'http://double-underscore.googlecode.com/svn'; 
  _SC.loaderModules = {};
  loadingList = _SC.loaderModules;

  if ((/KHTML/).test(ua)) {
    cua.webkit = true;
  } else if (/Opera/.test(ua)) {
    cua.opera = true;
  } else if (/MSIE/.test(ua)) {
    cua.IE = true;
  } else if (/Gecko/.test(ua)) {
    cua.Gecko = true;
  }

  var _loadFile = function(type,url,fn) {
    var head = _DOCUMENT.getElementsByTagName("head")[0];
   /* if (false && !inHead) {
      //loadFile while page loading
      if(type=="script"){
        _DOCUMENT.write('<scr'+'ipt src="'+url+'" type="text/javascript"><\/scr'+'ipt>')
      } else if(type=="css"){
        _DOCUMENT.write('<link href="'+url+'" type="text/css" rel="stylesheet"></link>')
      }
    } else {*/
      //loadFile after page is loaded, lots of loading may crash IE
      var node, usera = _SC.ua;
      fn=typeof fn == 'function' ? fn : function(){};
      if(type=="script"){
        node = _DOCUMENT.createElement('script');
        node.type = 'text/javascript';
        node.src = url;
        node.charset = 'utf-8';
      } else if(type=="css") {
        node = _DOCUMENT.createElement('link');
        node.type = 'text/css';
        node.rel = 'stylesheet';
        node.href = url;
        node.charset = 'utf-8';
      }
      if (usera.IE) {
        node.onreadystatechange = function() {
          var rs = this.readyState;
          if ("loaded" === rs || "complete" === rs) {
            fn();
          }
        };
      } else if (usera.webkit) {
        if (type === "script") {
          node.addEventListener("load", function() {
            fn();
          });
        } 
      } else {
        node.onload = function() {
          fn();
        }
      }
      head.appendChild(node);
   // }
  }, _loadModuleByName = function(modName,getObj) {
    var loadingItem = loadingList[":"+modName],
      type = loadingItem && loadingItem.detailObj && loadingItem.detailObj.type,
      fp;
   /* if (getObj && getObj.dynamic) {
      inHead = !!getObj.dynamic;
    }*/

    fp = loadingItem ? loadingItem.get(getObj) : modName; 
    if (!type) {
      type = fp.substr(fp.length-3).toLowerCase() == 'css' ?
        'css' : 'script';
    }

    if (_SC.debug) {
      fp += '?_t='+Math.random();
    }

    _loadFile(type, fp, getObj && getObj.onSuccess)
  }, 
  /**
   * usage : __.load('xxx', callback, obj), __.load('xxx yyy', obj), __.load(['xx', 'yy'], callback),
   * callback and obj could both be ignored
   * @param {string|array} n an url of js file or module names to load, array of module names will be load simultaneously, space seperated string of module names will be load in tandem
   * @param {function} onSuccess the onload call back, this parameter equals getObj.onSuccess, could be omitted
   * @param {object} getObj configuration
   * @config {function} onSuccess the onload call back
   * @config {string} version version, 0 mean trunk
   * @config {string} type css or js
   */
  _load = function(n,getObj) {
    var newObj, firstN;
    if (typeof getObj == 'function') {
      newObj = arguments[2] || {};
      newObj.onSuccess = getObj;
      getObj = newObj;
    }
    if (Object.prototype.toString.apply(n) === '[object Array]') {
      for (var i=0,j=n.length;i<j;i++) {
        _load(n[i], getObj);
      }
    } else {
      n = n.split(' ');
      firstN = n.shift();
      if (n.length >= 1)  {
        newObj = {};
        for (var at in getObj) {
          newObj[at] = getObj[at];
        }
        newObj['onSuccess'] = function() { _load(n.join(' '), getObj) };
      } else {
        newObj = getObj;
      }

      _loadModuleByName(firstN, newObj);
    }
  }, _LoadModule = function (modName, detailObj) {
    this.mname = modName;
    this.detailObj = detailObj || {};
  }, _addModule = function(n, cfg) {
    loadingList[":"+ n] = new _LoadModule(n, cfg);
  }; 

  _LoadModule.prototype.get = function(getObj) {
    getObj = getObj || {};

    if (this.detailObj.fullPath) {
      return this.detailObj.fullPath;
    }

    if (this.detailObj.afterBasePath) {
      return [_SC.loaderBase, this.detailObj.afterBasePath].join('/');
    }

    var isDebug = _SC.debug === true ? true : false,
      type = this.detailObj['type'] || 'js',
      //source = this.detailObj['source'] || 'DU',
      sBase, name = this.mname, module;

/*    switch (source) {
      case 'DU' :
        //product on double-undersocre, debug on local
        if (isDebug) {
          sBase = [_SC.loaderBase[0], type].join('/');
          name += '_comment';
        } else {
          sBase = _SC.loaderBase[1];
          var edition = _SC.DU_TAG ? _SC.DU_TAG :
            (getObj.version ? getObj.version : DU_TAG);
          if (edition == '0') { // load trunk
            sBase += '/trunk/src';
          } else { // load special tags
            sBase += '/tags/' + edition;
            //sBase = [_SC.loaderBase[1], edition].join('/');
          }
        }
        break;
      case 'ST' :
        //product on stauren.net, debug on local
          sBase = [_SC.loaderBase[0], type].join('/');
        if (isDebug) {
          name += '_comment';
        }
        break;
    }*/

    sBase = _SC.loaderBase;
    var edition = isDebug ? '0' : 
      (getObj.version ? getObj.version : 
      (_SC.DU_TAG ? _SC.DU_TAG : DU_TAG));
    if (edition == '0') { // load trunk
      sBase += '/trunk/src';
    } else { // load special tags
      sBase += '/tags/' + edition + '/pkgs';
    }
    
    module = getObj.module || name;

    name += type == 'css' ? '.css' : '.js';

    return [sBase, module, name].join('/')
  };


    _addModule('core');
    _addModule('yui', { afterBasePath : '/trunk/lib/YUI_ydecja.js' });
    _addModule('du');

    loadingList[":jslitmus"]=new _LoadModule("JSLitmus", {source:'DU'});
    loadingList[":stbase"]=new _LoadModule("staurennet", {source:'DU'});

    __.load = _load;
    __.addModule = _addModule;
}
})(window);
